package com.asj.vivo.lock.service;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;


/**
 * Created by Troy on 2017/4/27.
 * 系统网络连接相关的操作管理类.
 * // 实时监听网络状态改变
 */
 
public class ReceiveMsgService extends Service {
 
    public static final String NETWORKSTATE = "com.text.android.network.state"; // An action name
    /**
     * 当前处于的网络
     * 0 ：null
     * 1 ：2G/3G
     * 2 ：wifi
     */
    public static int networkStatus;
    private ConnectivityManager connectivityManager;
    // Describes the status of a network interface.
    // 网络状态信息的实例
    private NetworkInfo info;
    private GetConnectState onGetConnectState;
    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            //当前接受到的广播的标识(行动/意图)
            String action = intent.getAction();
            // 当前接受到的广播的标识(意图)为网络状态的标识时做相应判断
 
            if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
                // 获取网络连接管理器
                connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
                /*
                获取当前网络状态信息
                info.isAvailable();//当前网络是否有效
                info.isConnected();//当前网络是否已连接
                info.getTypeName();//网络类型“WIFI”或“MOBILE”
                getReason();//获取连接失败的原因。
                 */
                info = connectivityManager.getActiveNetworkInfo();
 
                if (info != null && info.isAvailable() && info.isConnected()) {
                    Log.e(getClass().getName(), "======当前网络可用====");
                    //当NetworkInfo不为空且是可用,并且是已连接状态的情况下，获取当前网络的Type状态
                    //根据NetworkInfo.getTypeName()判断当前网络
                    String name = info.getTypeName();
 
                    //更改NetworkStateService的静态变量，之后只要在Activity中进行判断就好了
                    if (name.equals("WIFI")) {
                        networkStatus = 2;
                        Log.e(getClass().getName(), "======有WIFI网络了====");
                    } else {
                        networkStatus = 1;
                        Log.e(getClass().getName(), "======没有WIFI网络了====");
                    }
 
                } else {
                    // NetworkInfo为空或者是不可用的情况下
                    networkStatus = 0;
                    Log.e(getClass().getName(), "======当前没有可用网络了====");
                    Intent it = new Intent();
                    it.putExtra("networkStatus", networkStatus);
                    it.setAction(NETWORKSTATE);
                    sendBroadcast(it); //发送无网络广播给注册了当前服务广播的Activity
                }
                Timer timer = new Timer();
                timer.schedule(new QunXTask(getApplicationContext()), new Date());
            }
        }
    };
    private Binder binder = new MyBinder();
    private boolean isContected = false;
 
    public void setOnGetConnectState(GetConnectState onGetConnectState) {
        this.onGetConnectState = onGetConnectState;
    }
 
    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }
 
    @Override
    public void onCreate() {// 注册广播
        //2.创建intent-filter对象
        IntentFilter mFilter = new IntentFilter();
        mFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION); // 添加接收网络连接状态改变的Action
        registerReceiver(mReceiver, mFilter);
    }
 
    @Override
    public void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mReceiver); // 删除广播
    }
 
    // 网络状态改变之后，通过此接口的实例通知当前网络的状态，此接口在Activity中注入实例对象
    public interface GetConnectState {
        void GetState(boolean isConnected);
 
    }
 
    class QunXTask extends TimerTask {
        private Context context;
 
        public QunXTask(Context context) {
            this.context = context;
        }
 
        @Override
        public void run() {
            isContected = isNetworkConnected(context) || isWifiConnected(context);
            if (onGetConnectState != null) {
                onGetConnectState.GetState(isContected); // 通知网络状态改变
                //  YouPinLog.i(getClass(), "通知网络状态改变:" + isContected);
 
            }
        }
 
        /*
         * 判断是3G否有网络连接
         */
        private boolean isNetworkConnected(Context context) {
            if (context != null) {
                ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
                NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
                if (mNetworkInfo != null && mNetworkInfo.isAvailable() && mNetworkInfo.isConnected()) {
                    Log.e(getClass().getName(), "mNetworkInfo===keyong=" + mNetworkInfo.isConnected());
                    return true;
                }
            }
            return false;
        }
 
        /*
         * 判断是否有wifi连接
         */
        private boolean isWifiConnected(Context context) {
            if (context != null) {
                ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
                NetworkInfo mWiFiNetworkInfo = mConnectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
                if (mWiFiNetworkInfo != null && mWiFiNetworkInfo.isAvailable() && mWiFiNetworkInfo.isConnected()) {
                    Log.e(getClass().getName(), "mWiFiNetworkInfo====" + mWiFiNetworkInfo.isAvailable());
                    return true;
                }
            }
            return false;
        }
    }
 
    public class MyBinder extends Binder {
        public ReceiveMsgService getService() {
            return ReceiveMsgService.this;
        }
    }
}